﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DAWSharp.DSP.EQ
{
    public class Peak : EQ
    {
        /// <summary>
        /// Sets initial values for BiQuad Peaking EQ according to http://www.musicdsp.org/files/Audio-EQ-Cookbook.txt
        /// </summary>
        /// <param name="cf">Center Frequency</param>
        /// <param name="BW">Bandwidth</param>
        /// <param name="dBGain">Gain in Decibels</param>
        /// <param name="sampleFrequency">Sample frequency</param>
        public Peak(float cf, float BW, float dBGain, float sampleFrequency)
        {
            w0 = 2.0f * Math.PI * (cf / sampleFrequency);
            sinw0 = Math.Sin(w0);
            cosw0 = Math.Cos(w0);
            A = Math.Pow(10.0f, (dBGain / 40.0f));
            alpha = sinw0 * Math.Sinh(Math.Log(2) / 2 * BW * w0 / sinw0);

            b0 = 1 + alpha * A;
            b1 = -2 * cosw0;
            b2 = 1 - alpha * A;
            a0 = 1 + alpha / A;
            a1 = -2 * cosw0;
            a2 = 1 - alpha / A;

            b0a0 = b0 / a0;
            b1a0 = b1 / a0;
            b2a0 = b2 / a0;
            a1a0 = a1 / a0;
            a2a0 = a2 / a0;
        }

        /// <summary>
        /// Updates values for BiQuad Peaking EQ according to http://www.musicdsp.org/files/Audio-EQ-Cookbook.txt
        /// </summary>
        /// <param name="cf">Center Frequency</param>
        /// <param name="BW">Bandwidth</param>
        /// <param name="dBGain">Gain in Decibels</param>
        /// <param name="sampleFrequency">Sample frequency</param>
        public void SetValues(float cf, float BW, float dBGain, float sampleFrequency)
        {
            w0 = 2.0f * Math.PI * (cf / sampleFrequency);
            sinw0 = Math.Sin(w0);
            cosw0 = Math.Cos(w0);
            A = Math.Pow(10.0f, (dBGain / 40.0f));
            alpha = sinw0 * Math.Sinh(Math.Log(2) / 2 * BW * w0 / sinw0);

            b0 = 1 + alpha * A;
            b1 = -2 * cosw0;
            b2 = 1 - alpha * A;
            a0 = 1 + alpha / A;
            a1 = -2 * cosw0;
            a2 = 1 - alpha / A;

            b0a0 = b0 / a0;
            b1a0 = b1 / a0;
            b2a0 = b2 / a0;
            a1a0 = a1 / a0;
            a2a0 = a2 / a0;
        }
    }
}
